<?php
/**
* Process the user login by checking username/password against the DB
*
* @author       Fabrice Douteaud <clearbudget@douteaud.com>
* @package      actions
* @access       public
*/

/***********************************************************************

  Copyright (C) 2008  Fabrice douteaud (clearbudget@douteaud.com)

    This file is part of ClearBudget.

    ClearBudget is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ClearBudget is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ClearBudget.  If not, see <http://www.gnu.org/licenses/>.


************************************************************************/
//prevent direct access
if(!defined('ENGINEON')) die('Direct access forbidden');

// if site is not supposed to be secured, we go directly to the home page
if(!class_settings::secureAccess()) {
  $context->nextAction = 'home';
  return;
  }

// some flag
$badUsername = false;
$badPassword = false;
$logoutSuccess = false;

// get the input values
$username = $context->username;
$password = $context->password;
$backAction = $context->backAction;
class_debug::addMsg(__FILE__, 'backAction is "'.$backAction.'"', DEBUGDEBUG);

// if the user is logged in, we log him out
if (class_context::isUserLoggedIn()) {
  $logoutSuccess = true;
  class_userCookie::deleteCookie();
  }

// if the user did not submit, we simply go to the view
$submitFlag = $context->submit;
if($submitFlag == null) {
  return;
  }

// let's try to login
$userId = class_settings::checkCredentials($username, $password);
if($userId === false) {
   $badUsername = true;
   $badPassword = true;
   }
else {
  // log the user in
  class_controller::loginUser();
  // next is to go to the previous action
  if($backAction == '' || $backAction == 'login') $backAction = 'home';
  $context->nextAction = $backAction;
  $context->redirect($backAction);
  // unset the submit flag
  $submitFlag = null;
  }
?>